package com.tech.platform.cms.databases.mybatis.sqlParser.tenantParser;

import cn.hutool.core.util.ObjectUtil;
import com.tech.platform.cms.databases.mybatis.bean.TenantProperties;
import com.tech.platform.cms.databases.mybatis.config.MybatisExtendProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collections;
import java.util.List;

/**
 * @author shengqiang.wu
 * @date 2019/12/24/024 10:25
 * @desc
 */
@Configuration
@ConditionalOnProperty(prefix = "mybatis-extend",name = "use-tenant",havingValue = "true")
public class TenantWebAdapter implements WebMvcConfigurer{

    @Autowired
    private MybatisExtendProperties mybatisExtendProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        TenantProperties tenantProperties = mybatisExtendProperties.getTenantProperties();
        List<String> excludeUrls = Collections.emptyList();
        if(tenantProperties!=null){
            excludeUrls = tenantProperties.getExcludeUrls();
        }

        registry.addInterceptor(tenantWebInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludeUrls)
                .order(Integer.MAX_VALUE);//这里之所以优先级设置到最后,是问了方便用户鉴权是,动态赋值tenant
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    private TenantWebInterceptor tenantWebInterceptor(){
        TenantProperties tenantProperties = mybatisExtendProperties.getTenantProperties();
        TenantWebInterceptor tenantWebInterceptor = new TenantWebInterceptor();
        if(ObjectUtil.isNotNull(tenantProperties)){
            tenantWebInterceptor.setInterceptType(tenantProperties.getInterceptType());
            tenantWebInterceptor.setInterceptKey(tenantProperties.getInterceptKey());
        }
        return tenantWebInterceptor;
    }
}
